const { app, BrowserWindow, Menu, ipcMain, dialog, protocol } = require('electron')
const path = require('node:path')
const fs = require('fs');
const log4js = require('log4js')
const logger = log4js.getLogger();
const url = require("url");
// process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = true;

async function createWindow() {
    const win = new BrowserWindow({
        width: 1280,
        height: 900,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            webSecurity:false
        },
        title: 'check456',
        titleBarStyle: 'hidden',//'hidden',
        // resizable:false
    })

    win.loadURL(`app://./dist1/index.html`) 
    // win.loadURL(`http://localhost:5173/`)
    // win.loadURL('http://localhost:5173')
    // win.loadFile('./dist/index.html')

    win.webContents.openDevTools();

    // console.log(await dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))
    ipcMain.on('openFile', (event, arg) => {
        console.log(arg)
        event.sender.send('selected-file', arg)
    })

    ipcMain.on('chooseFile', (args) => {
        dialog.showOpenDialog({ properties: ['openFile'] }).then(result => {
            win.webContents.send("chooseFile", result)
        })
    })
    ipcMain.on('chooseDir', (args) => {
        dialog.showOpenDialog({ properties: ['openDirectory'] }).then(result => {
            win.webContents.send("chooseDir", result)
        })
    })

}
Menu.setApplicationMenu(null)

app.whenReady().then(() => {


    protocol.registerBufferProtocol("app", (request, respond) => {

        console.log(request.url)
        // console.log(url.parse(request.url))

        let pathName = new URL(request.url).pathname


        pathName = decodeURI(pathName) // Needed in case URL contains spaces

        fs.readFile(path.join(__dirname, pathName), (error, data) => {
            if (error) {
                console.error(
                    `Failed to read ${pathName} on ${app} protocol`,
                    error
                )
            }
            const extension = path.extname(pathName).toLowerCase()
            let mimeType = ''

            if (extension === '.js') {
                mimeType = 'text/javascript'
            } else if (extension === '.html') {
                mimeType = 'text/html'
            } else if (extension === '.css') {
                mimeType = 'text/css'
            } else if (extension === '.svg' || extension === '.svgz') {
                mimeType = 'image/svg+xml'
            } else if (extension === '.json') {
                mimeType = 'application/json'
            } else if (extension === '.wasm') {
                mimeType = 'application/wasm'
            } else if (extension === '.woff') {
                mimeType = 'font/woff'
            }

            respond({ mimeType, data })
        })
    })

    createWindow()

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})
ipcMain.on('readFileSync', (args) => {
    logger.info(`readFileSync`, args)
    return fs.readFileSync(...args);
})
ipcMain.on('quit', () => {
    doQuit();
})



function doQuit() {
    logger.debug('app will quit');
    app.quit();
}
